package ac.github.os.internal.core.store

import ac.github.os.OriginSkill
import ac.github.os.util.getHost
import taboolib.module.database.ColumnTypeSQL
import taboolib.module.database.Table

class StorageSQL : Storage {

    companion object {
        const val DATA_KEY = "data_key"
        const val DATA_VALUE = "data_value"
    }

    val host by lazy { OriginSkill.config.getHost("options.mysql") }

    val table by lazy {
        Table(OriginSkill.config.getString("options.mysql.table") + "_data", host) {
            add { id() }
            add(DATA_KEY) { type(ColumnTypeSQL.VARCHAR, 255) }
            add(DATA_VALUE) { type(ColumnTypeSQL.VARCHAR, 255) }
        }
    }

    val dataSource = table.host.createDataSource()

    override fun load() {
        table.workspace(dataSource) { createTable() }.run()
        Store.GLOBAL = findStore()
    }

    override fun set(key: String, data: Store.Data) {
        if (table.find(dataSource) { where { DATA_KEY eq key } }) {
            table.update(dataSource) {
                where { DATA_KEY eq key }
                set(DATA_VALUE, data.asString())
            }
        } else {
            table.insert(dataSource, DATA_KEY, DATA_VALUE) { value(key, data.asString()) }
        }
    }

    override fun findStore(): Store {
        val store = Store()
        table.select(dataSource) { }.forEach {
            store.map[getString(DATA_KEY)] = Store.Data(getString(DATA_VALUE))
        }
        return store
    }

    override fun remove(key: String) {
        table.delete(dataSource) { where { DATA_KEY eq key } }
    }

}